import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Menu, message, Radio } from 'antd';

const { SubMenu } = Menu;


class SingleSelectableTreeMenus extends Component {

  static defaultProps = {
    mode: 'inline'
  };

  constructor(props) {
    super(props);
    this.state = {
      selectedKey: null
    }
  }

  handleRadioChange = (e) => {
    const selectedKey = e.target.value;
    this.setState({ selectedKey }, ()=>this.props.onSelectedMenuChange([selectedKey]));
  }

  buildMenuNodes = (menuList) => {
    if(!menuList) {
      message.error('查询菜单节点不能为空');
      return [];
    }
    return menuList.map(item => {
      if (!item.children) {
        return (
          <Menu.Item key={item.key}>
            <Radio value={item.key} onClick={e=>e.stopPropagation()}>{item.title}</Radio>
          </Menu.Item>
        )
      } else {
        return (
          <SubMenu
            key={item.key}
            title={item.title}
          >
            {this.buildMenuNodes(item.children)}
          </SubMenu>
        )
      }
    });
  };

  // componentWillReceiveProps(nextProps) {
  //   if(nextProps.menuList !== this.props.menuList) {
  //     this.setState({
  //       menuList: this.buildMenuKeys(nextProps.menuList),
  //       selectedList:[]
  //     });
  //   }
  // }

  render() {
    const { defaultSelectedKeys, defaultOpenKeys, mode, menuList } = this.props;
    return (
      <Radio.Group onChange={this.handleRadioChange}>
        <Menu
          mode={mode.toLowerCase()}
          defaultSelectedKeys={defaultSelectedKeys}
          defaultOpenKeys={defaultOpenKeys}
          selectable = {false}
        >
          {this.buildMenuNodes(menuList)}
        </Menu>
      </Radio.Group>
    );
  }
}

SingleSelectableTreeMenus.propTypes = {
  menuList: PropTypes.object.isRequired,
  defaultSelectedKeys: PropTypes.array,
  defaultOpenKeys: PropTypes.array,
  mode: PropTypes.string,
  onSelectedMenuChange: PropTypes.func.isRequired
};

export default SingleSelectableTreeMenus;
